// pages/minimall/minimall.js

import {reqListMerchandiseByAnchorId} from "../../api/liveroom"
import { reqMinimallDelete } from "../../api/minimall"

import {modal, toast} from "../../utils/extendApi"
import { getStorage } from "../../utils/storage"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods:[],
    manageshow:false
  },

  onShow(){
    this.showMerchandise()
  },

  onChangechecked(event) {
    const merchandiseId = event.currentTarget.dataset.id
    const list = this.data.goods
    for (let i = 0 ; i < list.length ; i++){
      if (list[i].merchandiseId == merchandiseId){
        list[i].checked=event.detail
        break
      }
    }

    this.setData({
      goods:list
    })
  },

  async showMerchandise(){
    const param={
      anchorId:getStorage('customerId')
    }
    const {data} = await reqListMerchandiseByAnchorId(param)

    let goods = data
    goods.forEach(item =>{
      item.checked=false
    })

    // console.log(data)
    this.setData({
      goods:goods
    })
  },

  onopenmanageshow(){
    let manageshow = this.data.manageshow
    manageshow = !manageshow 
    this.setData({
      manageshow:manageshow
    })
  },

  navigateToMerchandiseDetail(e){
    const id = e.currentTarget.dataset.productid
    wx.navigateTo({
      url: `/pages/good/good?productId=${id}`,
    })
  },

  navigatoToSearch(){
    const type='anchor'
    wx.navigateTo({
      url: `/pages/search/search?type=${type}`,
    })
  },

  async ensuredelete(){
    const res = await wx.modal({content:'确认删除商品？'})
    if (res) {
      this.deletemerchandise()
    }
  },

  async deletemerchandise(){
    let arr = this.data.goods
    let merchandiseIds = arr.filter(item => item.checked).map(item => item.merchandiseId)
    const param = {
      merchandiseIds:merchandiseIds
    }
    const {code} = await reqMinimallDelete(param)
    if(code){
      wx.toast({
        title:'删除成功',
        icon:'success'
      })
    }else{
      wx.toast({
        title:'删除失败',
        icon:'error'
      })
    }
    this.showMerchandise()
  }
})